<template>
  <div class="query-history">
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <span>查询历史</span>
          <div class="header-actions">
            <el-button type="danger" @click="clearHistory" :disabled="historyItems.length === 0"> 清空历史 </el-button>
          </div>
        </div>
      </template>

      <div v-if="loading" class="loading">
        <el-skeleton :rows="8" animated />
      </div>

      <el-alert v-else-if="error" :title="error" type="error" show-icon :closable="false" class="error-alert" />

      <div v-else-if="historyItems.length === 0" class="no-history">
        <el-empty description="暂无查询历史" />
      </div>

      <div v-else>
        <el-timeline>
          <el-timeline-item
            v-for="item in historyItems"
            :key="item.id"
            :timestamp="formatTime(item.queried_at)"
            placement="top"
          >
            <el-card class="history-item-card">
              <div class="history-item-content">
                <h4>{{ item.word }}</h4>
                <div class="item-tags">
                  <el-tag v-if="item.ielst === 'YES'" type="success" size="small" style="margin-right: 5px">
                    雅思词汇
                  </el-tag>
                  <el-tag v-if="item.ok === 'YES'" type="warning" size="small"> 已掌握 </el-tag>
                </div>
              </div>
              <div class="item-actions">
                <el-button type="primary" size="small" @click="searchWord(item.word)"> 重新查询 </el-button>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'QueryHistory',
  data() {
    return {
      historyItems: [],
      loading: false,
      error: null,
    };
  },
  async mounted() {
    await this.loadHistory();
  },
  methods: {
    async loadHistory() {
      this.loading = true;
      this.error = null;

      try {
        // Check if electronAPI is available
        if (typeof window.electronAPI !== 'undefined' && window.electronAPI.getQueryHistory) {
          const response = await window.electronAPI.getQueryHistory(50); // Get last 50 items

          if (response.success) {
            this.historyItems = response.data;
          } else {
            throw new Error(response.error || 'Failed to load query history');
          }
        } else {
          console.warn('Electron API not available, running in browser development mode');
          // For development, use mock data
          await new Promise(resolve => setTimeout(resolve, 500));

          // Mock data for demonstration
          this.historyItems = [
            { id: 1, word: 'abandon', queried_at: '2023-05-15T10:30:00Z', ielst: 'YES', ok: 'NO' },
            { id: 2, word: 'ability', queried_at: '2023-05-14T15:45:00Z', ielst: 'YES', ok: 'YES' },
            { id: 3, word: 'academic', queried_at: '2023-05-14T09:20:00Z', ielst: 'YES', ok: 'NO' },
            { id: 4, word: 'access', queried_at: '2023-05-13T14:10:00Z', ielst: 'YES', ok: 'NO' },
            { id: 5, word: 'accident', queried_at: '2023-05-12T11:55:00Z', ielst: 'YES', ok: 'YES' },
          ];
        }
      } catch (err) {
        console.error('Error loading query history:', err);
        this.error = err.message;
      } finally {
        this.loading = false;
      }
    },

    formatTime(timestamp) {
      const date = new Date(timestamp);
      return date.toLocaleString('zh-CN');
    },

    async clearHistory() {
      try {
        // Check if electronAPI is available
        if (typeof window.electronAPI !== 'undefined' && window.electronAPI.clearQueryHistory) {
          const response = await window.electronAPI.clearQueryHistory();

          if (response.success) {
            this.historyItems = [];
            this.$message.success('查询历史已清空');
          } else {
            throw new Error(response.error || 'Failed to clear query history');
          }
        } else {
          console.warn('Electron API not available, running in browser development mode');
          // For development, simulate the behavior
          await new Promise(resolve => setTimeout(resolve, 300));

          this.historyItems = [];
          this.$message.success('查询历史已清空');
        }
      } catch (err) {
        console.error('Error clearing query history:', err);
        this.$message.error('清空查询历史失败: ' + err.message);
      }
    },

    searchWord(word) {
      // Emit event to parent component to navigate to search page with the word
      this.$emit('search-word', word);
    },
  },
};
</script>

<style scoped>
.query-history {
  max-width: 800px;
  margin: 0 auto;
}

.history-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-item-card {
  margin-bottom: 10px;
}

.history-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.history-item-content h4 {
  margin: 0;
  color: #333;
}

.item-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.item-actions {
  margin-top: 10px;
}

.error-alert {
  margin: 20px 0;
}

.no-history {
  padding: 40px 0;
}
</style>
